package com.dodo.blog.ui.util;

import com.dodo.blog.exception.ValidationException;
import com.dodo.blog.model.Account;
import com.dodo.blog.model.groups.ClassicLoginTypeGroup;
import com.dodo.blog.model.groups.EditAccountGroup;
import com.dodo.blog.model.groups.OpenIdLoginTypeGroup;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class ValidationUtil
{
    public enum ValidationFactory
    {
        SINGLE_INSTANCE
                {
                    ValidatorFactory validationFactory = Validation.buildDefaultValidatorFactory();

                    @Override
                    public Validator getValidator()
                    {
                        return validationFactory.getValidator();
                    }
                };

        public abstract Validator getValidator();
    }

    public static <T> void validate( T object, Class... groups ) throws ValidationException
    {
        Set<ConstraintViolation<T>> constraintViolations = ValidationFactory.SINGLE_INSTANCE.getValidator().validate( object, groups );
        if ( !constraintViolations.isEmpty() )
        {
            throw new ValidationException( constraintViolations );
        }
    }

    public static void validateRegistration( Account account ) throws ValidationException
    {
        List<Class> groups = new ArrayList<Class>();

        switch ( account.getLoginType() )
        {
            case OPEN_ID:
            case OAUTH:
            {
                groups.add( OpenIdLoginTypeGroup.class );
                break;
            }
            case LOGIN:
            {
                groups.add( ClassicLoginTypeGroup.class );
                break;
            }
        }

        groups.add( EditAccountGroup.class );
        validate( account, groups.toArray( new Class[]{} ) );
    }

    public static void validateEditAccount( Account account ) throws ValidationException
    {
        validate( account, EditAccountGroup.class );
    }
}
